// 购物车管理模块
import { getUserInfo, setUserInfo } from './user.js';
import { showNotification } from './notification.js';

/**
 * 获取购物车数据
 * @returns {Array} 购物车商品数组
 */
export function getCart() {
    const cartStr = localStorage.getItem('cart');
    return cartStr ? JSON.parse(cartStr) : [];
}

/**
 * 设置购物车数据
 * @param {Array} cart 购物车商品数组
 */
export function setCart(cart) {
    localStorage.setItem('cart', JSON.stringify(cart));
}

/**
 * 添加商品到购物车
 * @param {string} id 商品ID
 * @param {string} name 商品名称
 * @param {number} price 商品价格
 * @param {number} points 商品积分
 */
export function addToCart(id, name, price, points) {
    const cart = getCart();
    const existingItem = cart.find(item => item.id === id);
    
    if (existingItem) {
        existingItem.quantity += 1;
    } else {
        cart.push({
            id,
            name,
            price,
            points,
            quantity: 1
        });
    }
    
    setCart(cart);
    updateCartCount();
}

/**
 * 从购物车移除商品
 * @param {string} id 商品ID
 */
export function removeFromCart(id) {
    const cart = getCart();
    const newCart = cart.filter(item => item.id !== id);
    setCart(newCart);
    updateCart();
    updateCartCount();
}

/**
 * 更新购物车商品数量
 * @param {string} id 商品ID
 * @param {number} quantity 新数量
 */
export function updateCartItemQuantity(id, quantity) {
    if (quantity < 1) return;
    
    const cart = getCart();
    const item = cart.find(item => item.id === id);
    
    if (item) {
        item.quantity = quantity;
        setCart(cart);
        updateCart();
        updateCartCount();
    }
}

/**
 * 清空购物车
 */
export function clearCart() {
    localStorage.removeItem('cart');
    updateCart();
    updateCartCount();
}

/**
 * 更新购物车数量显示
 */
export function updateCartCount() {
    const cart = getCart();
    const cartCount = document.getElementById('cart-count');
    
    if (cartCount) {
        const totalItems = cart.reduce((sum, item) => sum + item.quantity, 0);
        cartCount.textContent = totalItems;
        cartCount.classList.toggle('hidden', totalItems === 0);
    }
}

/**
 * 更新购物车内容显示
 */
export function updateCart() {
    const cart = getCart();
    const cartItems = document.getElementById('cart-items');
    const emptyCart = document.getElementById('empty-cart');
    const cartTotal = document.getElementById('cart-total');
    const checkoutBtn = document.getElementById('checkout-btn');
    
    if (!cartItems || !emptyCart || !cartTotal) return;
    
    // 清空现有内容
    while (cartItems.firstChild) {
        if (cartItems.firstChild === emptyCart) {
            break;
        }
        cartItems.removeChild(cartItems.firstChild);
    }
    
    if (cart.length === 0) {
        emptyCart.classList.remove('hidden');
        cartTotal.textContent = '¥0';
        if (checkoutBtn) {
            checkoutBtn.disabled = true;
        }
        return;
    }
    
    emptyCart.classList.add('hidden');
    
    // 添加购物车商品
    let total = 0;
    
    cart.forEach(item => {
        const itemTotal = item.price * item.quantity;
        total += itemTotal;
        
        const itemEl = document.createElement('div');
        itemEl.className = 'flex items-center border-b pb-4';
        itemEl.innerHTML = `
            <div class="flex-1 min-w-0">
                <h4 class="font-medium truncate">${item.name}</h4>
                <div class="flex justify-between items-center mt-2">
                    <div>
                        <span class="text-primary font-bold">¥${item.price.toFixed(2)}</span>
                        <span class="text-gray-400 text-xs ml-2">+${item.points * item.quantity}积分</span>
                    </div>
                    <div class="flex items-center space-x-2">
                        <button class="quantity-btn decrease w-6 h-6 rounded-full bg-gray-100 flex items-center justify-center text-gray-600 hover:bg-gray-200 transition-colors" data-id="${item.id}">
                            <i class="fa fa-minus text-xs"></i>
                        </button>
                        <span class="quantity" data-id="${item.id}">${item.quantity}</span>
                        <button class="quantity-btn increase w-6 h-6 rounded-full bg-gray-100 flex items-center justify-center text-gray-600 hover:bg-gray-200 transition-colors" data-id="${item.id}">
                            <i class="fa fa-plus text-xs"></i>
                        </button>
                    </div>
                </div>
            </div>
            <button class="remove-item-btn w-8 h-8 flex items-center justify-center text-gray-400 hover:text-danger transition-colors ml-2" data-id="${item.id}">
                <i class="fa fa-trash"></i>
            </button>
        `;
        
        cartItems.appendChild(itemEl);
    });
    
    cartTotal.textContent = `¥${total.toFixed(2)}`;
    
    if (checkoutBtn) {
        checkoutBtn.disabled = !getUserInfo();
        checkoutBtn.addEventListener('click', handleCheckout);
    }
    
    // 添加数量调整按钮事件
    document.querySelectorAll('.quantity-btn.decrease').forEach(btn => {
        btn.addEventListener('click', (e) => {
            const id = e.target.closest('.decrease').dataset.id;
            const quantityEl = document.querySelector(`.quantity[data-id="${id}"]`);
            let quantity = parseInt(quantityEl.textContent);
            if (quantity > 1) {
                updateCartItemQuantity(id, quantity - 1);
            }
        });
    });
    
    document.querySelectorAll('.quantity-btn.increase').forEach(btn => {
        btn.addEventListener('click', (e) => {
            const id = e.target.closest('.increase').dataset.id;
            const quantityEl = document.querySelector(`.quantity[data-id="${id}"]`);
            let quantity = parseInt(quantityEl.textContent);
            updateCartItemQuantity(id, quantity + 1);
        });
    });
    
    // 添加删除按钮事件
    document.querySelectorAll('.remove-item-btn').forEach(btn => {
        btn.addEventListener('click', (e) => {
            const id = e.currentTarget.dataset.id;
            removeFromCart(id);
        });
    });
}

/**
 * 处理结算
 */
export function handleCheckout() {
    const user = getUserInfo();
    if (!user) {
        showNotification('请先登录', '登录后才能结算', 'error');
        return;
    }
    
    const cart = getCart();
    if (cart.length === 0) {
        showNotification('购物车为空', '请先添加商品到购物车', 'error');
        return;
    }
    
    // 计算总积分
    const totalPoints = cart.reduce((sum, item) => sum + (item.points * item.quantity), 0);
    
    // 更新用户积分
    user.points += totalPoints;
    setUserInfo(user);
    
    // 生成订单
    const order = {
        id: Date.now().toString(),
        items: [...cart],
        totalPrice: cart.reduce((sum, item) => sum + (item.price * item.quantity), 0),
        totalPoints,
        date: new Date().toISOString()
    };
    
    // 保存订单历史
    const orders = JSON.parse(localStorage.getItem('orders') || '[]');
    orders.unshift(order);
    localStorage.setItem('orders', JSON.stringify(orders));
    
    // 清空购物车
    clearCart();
    
    // 关闭购物车弹窗
    const cartModal = document.getElementById('cart-modal');
    if (cartModal) {
        cartModal.classList.add('hidden');
    }
    
    // 显示成功通知
    showNotification('订单成功', `购物成功！获得${totalPoints}积分`, 'success');
    
    // 更新用户信息
    import('./user.js').then(({ updateUserInfo }) => {
        updateUserInfo();
    });
    
    // 跳转到订单页面
    setTimeout(() => {
        window.location.href = 'orders.html';
    }, 1500);
}